define(['app','assets/js/zTree'],function(app){
    return {module: function($scope, $http, eventBusService, httpService, params, configService) {
        $scope.form = {};
        $scope.form.menu_id = params.father_id;
        var currentNode = null;
        var zTreeObj;
        var tId = "";
        
        httpService.post(app.urls.menu_select,{"id" : $scope.form.menu_id}, function(data) {
    		if("0000" === data.code){
    			$scope.menu_name = data.data[0].name;
    		}else{
    			alert(data.msg);
    		}
    	});
        
	    //按钮列表
		httpService.post(app.urls.button_select,{"menu_id" : $scope.form.menu_id}, function(data) {
			if("0000" === data.code){
				$scope.buttonList = data.data;
			}else{
				alert(data.msg);
			}
		});
        
        //学段
        httpService.post(app.urls.stage_selectAll, {}, function(data) {
            $scope.stageList = data.data;
            $scope.$apply();
            if(params.stage != null && params.stage != "") {
                $scope.form.fk_stage = params.stage;
            }else{
                $scope.form.fk_stage = $scope.stageList[0].id;
            }
            getSubject();
        });

        //学科
        var getSubject = function() {
            httpService.post(app.urls.subject_selectAll, {}, function(data) {
                $scope.subjectList = data.data;
                $scope.$apply();
                if(params.subject != null && params.subject != "") {
                    $scope.form.fk_subject = params.subject;
                }else{
                	for(var i = 0; i < $scope.subjectList.length; i++) {
                		if($scope.subjectList[i].fk_stage == $scope.form.fk_stage) {
                			$scope.form.fk_subject = $scope.subjectList[i].id;
                			break;
                		}
                	}
                }
                $('#' + $scope.controllerName + ' .subject_'+$scope.form.fk_subject+' a').addClass('selected');

                changeNavSubject();
            });
        }

        //选择学段学科
        $scope.subjectTabSelected = function(obj) {
            $scope.form.fk_stage = obj.fk_stage;
            $scope.form.fk_subject = obj.id;
            $('#' + $scope.controllerName + ' #subject li a').removeClass("selected");
            $('#' + $scope.controllerName + ' #subject .subject_'+$scope.form.fk_subject+" a").addClass('selected');

            changeNavSubject();
        }

        //更换学段学科
        var changeNavSubject = function() {
            var str = $('#' + $scope.controllerName +  ' .stage_'+$scope.form.fk_stage).text() + $('#' + $scope.controllerName + ' .subject_'+$scope.form.fk_subject+" a").text();
            $('#' + $scope.controllerName + ' #spanSubject').text(str.trim());

            currentNode = null;
            getVersionList();
        }

        //教材
        var getVersionList = function() {
            httpService.post(app.urls.version_selectBySubject, {
                "fk_subject" : $scope.form.fk_subject
            }, function(data) {
                $scope.materialList =  data.data;
                $scope.$apply();
                if($scope.materialList.length > 0) {
	                $scope.form.fk_version = $scope.materialList[0].id;
	                $('#material .material_'+$scope.form.fk_version+' a').addClass('selected');
	
	                getTextbookList();
                }
            });
        }

        //课本
        var getTextbookList = function() {
            httpService.post(app.urls.textbook_selectByVersion, {
                "fk_version" : $scope.form.fk_version
            }, function(data) {
                $scope.textbookList = data.data;
                $scope.$apply();
                $scope.form.fk_textbook = $scope.textbookList[0].id;
                $('#textbook .textbook_'+$scope.form.fk_textbook+' a').addClass('selected');

                changeTreeHead();
            });
        }

        //选择教材
        $scope.materialTabSelected = function(obj) {
            $('#material > li a').removeClass("selected");
            $('#material .material_'+obj.id+' a').addClass('selected');
            $scope.form.fk_version = obj.id;

            getTextbookList();
        }

        //选择课本
        $scope.textbookTabSelected = function(obj) {
            $('#textbook > li a').removeClass("selected");
            $('#textbook .textbook_'+obj.id+' a').addClass('selected');
            $scope.form.fk_textbook = obj.id;

            changeTreeHead();
        }

        //更换教材版本或者课本
        var changeTreeHead = function() {
            $('#spanEditor').text($('.material_'+$scope.form.fk_version).text().trim());
            $('#spanGrade').text($('.textbook_'+$scope.form.fk_textbook+" a").text().trim());

            currentNode = null;
            queryChapter();
        }

        $scope.find = function() {
            if(currentNode == null || currentNode == "") {
                httpService.postpage(app.urls.chapter_selectByTextbook, {"fk_textbook" : $scope.form.fk_textbook}, function(data){
                    if("0000" === data.code) {
                        $scope.dataList = data.data;
                        $('.nodeOperate2').css("display", "none");
                        $('.nodeOperate1').css("display", "block");
                    }else{
                        eventBusService.publish("modal.alert", {"content":data.msg});
                    }
                });
            }else{
                httpService.postpage(app.urls.chapter_selectThisAndChildrenNode, {"node_id" : currentNode.id}, function(data){
                    if("0000" === data.code) {
                        $scope.dataList = data.data;
                        $scope.$apply();

                        $('.nodeOperate2').css("display", "block");
                        $('.nodeOperate1').css("display", "none");
                        $('#'+currentNode.id).prop("checked", true);
                    }else{
                        eventBusService.publish("modal.alert", {"content":data.msg});
                    }
                });
            }
        }

        //检查当前是否有选中节点
        var currentNodeChecked = function() {
            if(currentNode == null || currentNode == "") {
                eventBusService.publish("modal.alert", {"content":"请选择知识点。"});
                return true;
            }
        }
        
        //按钮事件
        $scope.operate = function(event) {
            $scope[event]();
        }

        //新增节点
        $scope.add = function() {
            eventBusService.publish("modal.page","modules/content/baseinfo/chapter/input?fk_textbook="+$scope.form.fk_textbook);
        }

        //添加同级节点
        $scope.addSameNode = function() {
            eventBusService.publish("modal.page","modules/content/baseinfo/chapter/add?id="+currentNode.id+"&levelType=1");
        }

        //添加子节点
        $scope.addChildrenNode = function() {
            eventBusService.publish("modal.page","modules/content/baseinfo/chapter/add?id="+currentNode.id+"&levelType=2");
        }

        //更新节点序号
        var updateNodeOrderNumber = function(nodes) {
            httpService.post(app.urls.chapter_updateOrderNumber,{"nodes":JSON.stringify(nodes)}, function(data) {
                if(data.code=="0000"){
                    eventBusService.publish("content.page.reload", data.data);
                }else{
                    eventBusService.publish("modal.alert", {"content":data.msg});
                }
            });
        }

        //上移节点
        $scope.moveUp = function() {
            if(currentNode.getIndex() == 0) {
                eventBusService.publish("modal.alert", {"content":"不允许上移。"});
                return;
            }

            var moveNodes = [];
            var currentOrderNumber = parseInt(currentNode.orderNumber);
            currentNode.orderNumber = currentOrderNumber - 1;
            currentNode.getPreNode().orderNumber = currentOrderNumber;
            moveNodes.push(currentNode);
            moveNodes.push(currentNode.getPreNode());

            tId = currentNode.getPreNode().tId;
            updateNodeOrderNumber(moveNodes);
        }

        //下移节点
        $scope.moveDown = function() {
            if(currentNode.parentId == '0') {
                if (currentNode.getIndex() == zTreeObj.getNodes().length - 1) {
                    eventBusService.publish("modal.alert", {"content":"不允许下移。"});
                    return;
                }
            }else{
                if (currentNode.getIndex() == currentNode.getParentNode().children.length - 1) {
                    eventBusService.publish("modal.alert", {"content":"不允许下移。"});
                    return;
                }
            }

            var moveNodes = [];
            var currentOrderNumber = parseInt(currentNode.orderNumber);
            currentNode.orderNumber = currentOrderNumber + 1;
            currentNode.getNextNode().orderNumber = currentOrderNumber;
            moveNodes.push(currentNode);
            moveNodes.push(currentNode.getNextNode());

            //下移的距离
            tId = currentNode.tId;
            var childNodes = zTreeObj.transformToArray(currentNode.getNextNode());
            var subStr = tId.substring(tId.lastIndexOf("_")+1, tId.length);
            tId = tId.substring(0, tId.lastIndexOf("_")+1) + (parseInt(subStr) + childNodes.length);

            updateNodeOrderNumber(moveNodes);
        }

        //节点重命名
        $scope.edit = function() {
            eventBusService.publish("modal.page","modules/content/baseinfo/chapter/edit?id="+currentNode.id);
        }

        //删除节点
        $scope.remove = function() {
            eventBusService.publish("modal.alert", {"content":"删除此节点将同时删除该节点下所有子节点，删除后不可恢复，是否确认删除？", "isAutoClose":false,
                "confirm":function(){
                    httpService.post(app.urls.chapter_remove,{"node_id":currentNode.id}, function(data) {
                        if(data.code=="0000"){
                            tId = currentNode.tId;
                            var subStr = tId.substring(tId.lastIndexOf("_")+1, tId.length);
                            tId = tId.substring(0, tId.lastIndexOf("_")+1) + (parseInt(subStr) - 1);
                            eventBusService.publish("content.page.reload", data.data);
                        }else{
                            eventBusService.publish("modal.alert", {"content":"删除失败。"});
                        }
                    });
                }
            });
        }

        var zTreeOnClick = function(event, treeId, treeNode) {
            currentNode = treeNode;
            tId = currentNode.tId;

            $('#zTree li a').removeClass("curSelectedNode");
            $('#zTree #'+treeNode.tId+"_a").addClass("curSelectedNode");

            $('.nodeOperate1').css("display", "none");
            $('.nodeOperate2').css("display", "block");
            $scope.select();
        };

        // zTree 的参数配置，深入使用请参考 API 文档（setting 配置详解）
        var setting = {
            data: {
                simpleData: {
                    enable: true
                }
            },
            view:{
                showIcon: false
            },
            callback: {
                onClick: zTreeOnClick
            }
        };
        // zTree 的数据属性，深入使用请参考 API 文档（zTreeNode 节点数据详解）

        //查询知识点
        var queryChapter = function(){
            httpService.post(app.urls.chapter_selectByTextbook, $scope.form, function(data){
                if("0000" === data.code) {

                    var zNodes =  [];
                    for (var i = 0; i < data.data.length; i++) {
                        zNodes[i] = {};
                        zNodes[i].id = data.data[i].node_id;
                        zNodes[i].pId = data.data[i].node_pid;
                        zNodes[i].name = data.data[i].node_text;
                        zNodes[i].orderNumber = data.data[i].order_number;
                        zNodes[i].parentId = data.data[i].node_pid;
                    }
                    zTreeObj = $.fn.zTree.init($("#zTree"), setting, zNodes);
                    $scope.$apply();

                    if(currentNode != null && currentNode != "") {
                        currentNode = zTreeObj.getNodeByTId(tId);
                        zTreeObj.expandNode(currentNode, true, true, true);
                        zTreeObj.selectNode(currentNode);
                        //$('#zTree #'+currentNode.tId+"_a").addClass("curSelectedNode");
                    }
                    $scope.find();
                }else{
                    alert(data.msg);
                }
            });
        }

        $scope.select = function() {
            $scope.page.current = 1;
            $scope.find();
        }

        //接收数据刷新
        eventBusService.subscribe('content.page.reload', function(event,data) {
            queryChapter();
        });
            
    }
}});